<template>
  <div class="container-filter" @click.stop @keydown.stop @keyup.stop @submit.stop.prevent>
    <div class="filter-section">
      <div class="form-group" :class="{ disabled: !selectedDestination }">
        
        
        <div class="form-header">
          <label class="form-label">
            选择配送容器 * 
            <span v-if="selectedContainers.length > 0" class="selected-count">
              (已选择 {{ selectedContainers.length }} 个)
            </span>
          </label>
          
          <!-- 容器码搜索框 -->
          <div v-if="selectedDestination && filteredContainers.length > 0" class="container-search">
            <div class="search-input-wrapper">
              <input 
                v-model="containerCodeSearch"
                type="text"
                placeholder="输入完整容器码进行精准查找..."
                class="search-input"
                @input="handleSearchInput"
                @keydown.enter.prevent="handleSearchEnter"
                @keydown.escape="clearSearch"
              />
              <div class="search-actions">
                <span v-if="containerCodeSearch && searchResultCount >= 0" class="search-count">
                  {{ searchResultCount }} 个匹配
                </span>
                <button 
                  v-if="containerCodeSearch" 
                  type="button"
                  @click="clearSearch"
                  class="clear-search-btn"
                  title="清除搜索"
                >
                  ×
                </button>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 已选择容器区域 -->
        <div v-if="selectedContainers.length > 0" class="selected-containers-section">
          <h4 class="selected-title">
            <span class="icon">✓</span>
            已选择的容器 ({{ selectedContainers.length }})
          </h4>
          <div class="selected-container-tags">
            <div 
              v-for="container in selectedContainers" 
              :key="`selected-${container.id}`"
              class="selected-container-tag"
              @click="removeSelectedContainer(container)"
            >
              <span class="container-code">{{ getContainerCodeDisplay(container) }}</span>
              <button 
                type="button"
                @click.stop="removeSelectedContainer(container)"
                class="remove-container-btn"
                title="点击取消选择此容器"
                aria-label="取消选择容器"
              >
                ×
              </button>
            </div>
          </div>
          <div class="selected-actions">
            <button 
              type="button"
              @click="clearAllSelectedContainers"
              class="clear-all-btn"
            >
              清空所有选择
            </button>
          </div>
          <div class="selected-hint">
            <small>💡 提示：点击容器标签或下方列表中的已选容器可以取消选择</small>
          </div>
        </div>

        <!-- 容器卡片列表 -->
        <div v-if="!selectedDestination" class="placeholder-message">
          请先在上方选择发运目的地
        </div>
        
        <div v-else-if="loadingContainers" class="loading-indicator">
          <div class="loading-spinner"></div>
          正在加载容器...
        </div>
        
        <div v-else-if="filteredContainers.length === 0" class="empty-message">
          <div v-if="containerCodeSearch">
            <div class="no-results-icon">🔍</div>
            <div class="no-results-text">未找到匹配的容器</div>
            <div class="no-results-hint">请检查容器码是否完整且正确，需要精准匹配完整容器码</div>
          </div>
          <div v-else>
            该目的地暂无可用容器
          </div>
        </div>
        
        <div v-else class="container-list">
          <div 
            v-for="container in filteredContainers" 
            :key="container.id"
            class="container-card"
            :class="{ 
              selected: isContainerSelected(container.id),
              'has-details': containerDetailsMap[container.id]
            }"
          >
            <div class="container-main" @click.stop.prevent="toggleContainer(container)">
              <div class="container-selection-indicator">
                <div class="selection-checkbox">
                  <input 
                    type="checkbox" 
                    :checked="isContainerSelected(container.id)"
                    @click.stop.prevent="toggleContainer(container)"
                  />
                </div>
                <div v-if="isContainerSelected(container.id)" class="selection-checkmark">
                  ✓
                </div>
              </div>
              <div class="container-info">
                <div class="container-id-wrapper">
                  <div class="container-id">{{ getContainerCodeDisplay(container) }}</div>
                  <div v-if="isContainerSelected(container.id)" class="selected-badge">已选择</div>
                </div>
                <div class="container-site" v-if="getContainerSiteInfo(container) && showContainerSites">
                  <strong>配送站点:</strong>
                  <span class="site-info">{{ getContainerSiteInfo(container) }}</span>
                </div>
              </div>
              <div class="container-actions">
                <button 
                  type="button"
                  v-if="isContainerSelected(container.id)"
                  @click.stop="toggleContainerDetails(container.id)"
                  class="toggle-details-btn"
                  :class="{ expanded: isContainerExpanded(container.id) }"
                >
                  <span class="toggle-icon">{{ isContainerExpanded(container.id) ? '▲' : '▼' }}</span>
                </button>
              </div>
            </div>
            
            <!-- 容器详情 -->
            <transition 
              name="details-slide"
              @enter="onDetailsEnter"
              @leave="onDetailsLeave"
            >
              <div 
                v-if="isContainerSelected(container.id) && isContainerExpanded(container.id)" 
                class="container-details-inline"
              >
                <div class="details-header">
                  <span v-if="loadingDetailsMap[container.id]" class="loading-text">加载中...</span>
                </div>
                
                <div v-if="loadingDetailsMap[container.id]" class="details-loading">
                  <div class="loading-spinner"></div>
                  正在加载详情数据...
                </div>
                
                <div v-else-if="containerDetailsMap[container.id]" class="details-content">
                  <div v-if="containerDetailsMap[container.id].length > 0" class="details-list">
                    <div class="item-count-badge">
                      {{ getTotalItems(containerDetailsMap[container.id]) }}
                    </div>
                    <div class="product-list">
                      <div 
                        v-for="(detail, index) in containerDetailsMap[container.id]" 
                        :key="index"
                        class="product-item"
                      >
                        <div class="product-info">
                          <div class="product-name">
                            {{ getProductName(detail) }}
                          </div>
                          <div class="product-quantity">
                            数量：{{ getProductQuantity(detail) }}
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div v-else class="no-details">
                    <div class="empty-icon">📦</div>
                  </div>
                </div>
              </div>
            </transition>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick, getCurrentInstance } from 'vue'
import deliveryApi from '../api/delivery.js'
import { CONTAINER_FIELDS, WORKSHEET_IDS, API_CONFIG, getFieldValue } from '../config/delivery-config.js'

// Props
const props = defineProps({
  deliverySites: {
    type: Array,
    default: () => []
  },
  modelValue: {
    type: Object,
    default: () => ({
      destination: '',
      container: ''
    })
  },
  externalDestination: {
    type: String,
    default: ''
  },
  initialContainers: {
    type: Array,
    default: () => []
  },
  showSelectedContainers: {
    type: Boolean,
    default: true
  },
  showContainerSites: {
    type: Boolean,
    default: true
  },
  // 新增：当前正在编辑的配送单ID（用于排除已被其他配送单使用的容器）
  editingDeliveryOrderId: {
    type: String,
    default: ''
  },
  // 新增：已被使用的容器码列表（其他配送单已选择的容器码）
  usedContainerCodes: {
    type: Array,
    default: () => []
  },
  // 新增：是否为修改配送单模式（修改模式下只显示待使用状态的容器）
  isModifyMode: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'container-selected'])

// 响应式数据
const selectedDestination = ref('')
const selectedContainers = ref([])
const allContainers = ref([])
const containerDetailsMap = ref({})
const loadingContainers = ref(false)
const loadingDetailsMap = ref({})
const expandedDetailsMap = ref({})

// 搜索相关
const containerCodeSearch = ref('')
const searchResultCount = ref(0)

// 计算属性
const filteredContainers = computed(() => {
  if (!selectedDestination.value || !allContainers.value.length) {
    searchResultCount.value = 0
    return []
  }
  
  console.log('=== 容器筛选开始 ===')
  console.log('选择的目的地:', selectedDestination.value)
  console.log('总容器数量:', allContainers.value.length)
  console.log('当前编辑的配送单ID:', props.editingDeliveryOrderId)
  console.log('已被使用的容器码列表:', props.usedContainerCodes)
  
  let containers = allContainers.value.filter(container => {
    // 1. 检查容器码是否已被其他配送单使用
    const containerCode = getContainerCodeDisplay(container)
    const isUsedByOthers = props.usedContainerCodes.includes(containerCode)
    const isSelected = isContainerSelected(container.id)
    
    console.log(`容器 ${container.id} (${containerCode}): 被其他配送单使用=${isUsedByOthers}, 当前已选择=${isSelected}`)
    
    // 如果容器已被其他配送单使用，且当前配送单没有选择它，则不显示
    if (isUsedByOthers && !isSelected) {
      console.log(`容器 ${containerCode} 已被其他配送单使用，不显示`)
      return false
    }
    
    // 2. 检查配送站点信息是否匹配 - 严格匹配
    const containerSiteInfo = getFieldValue(
      container.rawData || container, 
      CONTAINER_FIELDS.CONTAINER_SITE_INFO,
      ''
    ) || container.siteInfo || ''
    
    console.log(`容器 ${container.id}: 站点信息="${containerSiteInfo}", 目标站点="${selectedDestination.value}"`)
    
    // 严格站点匹配逻辑：只有站点信息完全匹配的容器才显示
    let siteMatches = false
    if (containerSiteInfo && containerSiteInfo.trim() !== '') {
      siteMatches = containerSiteInfo === selectedDestination.value
      console.log(`容器 ${container.id}: 站点严格匹配结果=${siteMatches}`)
    } else {
      // 如果容器没有配送站点信息，不显示
      console.log(`容器 ${container.id}: 站点信息为空，不显示`)
      siteMatches = false
    }
    
    // 3. 检查容器状态
    const containerStatus = getContainerStatus(container)
    
    console.log(`容器 ${container.id}: 状态="${containerStatus}", 已选择=${isSelected}`)
    
    // 4. 特殊处理：如果容器已被当前配送单选择，则不管站点匹配情况如何都显示（方便用户取消选择）
    if (isSelected) {
      console.log(`容器 ${container.id}: 已被当前配送单选择，强制显示以便取消选择`)
      
      if (props.isModifyMode) {
        // 修改模式下：已选择的容器也只显示使用中状态的容器（保持一致性）
        const statusMatches = isStatusInUseOnly(containerStatus)
        console.log(`修改模式 - 已选容器 ${container.id}: 状态匹配=${statusMatches}`)
        return statusMatches
      } else {
        // 创建模式下：已选择的容器可以显示装车中状态
        const statusMatches = isStatusInUseOrLoading(containerStatus)
        return statusMatches
      }
    }
    
    // 5. 对于未选择的容器，进行严格的站点和状态筛选
    let statusMatches = false
    
    if (props.isModifyMode) {
      // 修改模式下：只显示使用中状态的容器
      statusMatches = isStatusInUseOnly(containerStatus)
      console.log(`修改模式 - 容器 ${container.id}: 状态匹配=${statusMatches}`)
    } else {
      // 创建模式下：待选择的容器不显示装车中状态，只显示使用中状态
      statusMatches = isStatusInUse(containerStatus)
      console.log(`创建模式 - 容器 ${container.id}: 状态匹配=${statusMatches}`)
    }
    
    const finalMatch = siteMatches && statusMatches
    console.log(`容器 ${container.id}: 站点匹配=${siteMatches}, 状态匹配=${statusMatches}, 最终匹配=${finalMatch}`)
    
    return finalMatch
  })
  
  // 6. 根据容器码搜索进行精准筛选
  if (containerCodeSearch.value.trim()) {
    const searchTerm = containerCodeSearch.value.trim().toLowerCase()
    console.log('应用容器码搜索:', searchTerm)
    containers = containers.filter(container => {
      const containerCode = getContainerCodeDisplay(container).toLowerCase()
      const matches = containerCode === searchTerm
      console.log(`容器码搜索: "${containerCode}" ${matches ? '匹配' : '不匹配'} "${searchTerm}"`)
      return matches
    })
  }
  
  console.log('=== 容器筛选结果 ===')
  console.log('筛选后容器数量:', containers.length)
  console.log('匹配的容器ID:', containers.map(c => c.id))
  console.log('匹配的容器码:', containers.map(c => getContainerCodeDisplay(c)))
  console.log('=== 容器筛选结束 ===')
  
  searchResultCount.value = containers.length
  return containers
})

// 监听器 - 防止循环更新
const isUpdatingFromParent = ref(false) // 添加标志防止循环更新

watch(() => props.modelValue, (newValue) => {
  
  if (isUpdatingFromParent.value) {
    return
  }
  
  if (newValue) {
    isUpdatingFromParent.value = true // 设置标志
    
    selectedDestination.value = newValue.destination || ''
    // 处理多容器数据
    if (Array.isArray(newValue.containers)) {
      selectedContainers.value = newValue.containers
    } else if (newValue.container) {
      // 兼容单容器格式
      const container = allContainers.value.find(c => c.id === newValue.container)
      selectedContainers.value = container ? [container] : []
    } else {
      selectedContainers.value = []
    }
    
    // 延迟重置标志
    nextTick(() => {
      isUpdatingFromParent.value = false
    })
  }
}, { immediate: true, deep: true })

// 监听 allContainers 变化，重新同步选择状态
watch(allContainers, () => {
    const currentModelValue = props.modelValue
  if (currentModelValue && currentModelValue.container && allContainers.value.length > 0) {
    const container = allContainers.value.find(c => c.id === currentModelValue.container)
    if (container && !selectedContainers.value.some(c => c.id === container.id)) {
      console.log('重新同步容器选择:', container)
      selectedContainers.value = [container]
    }
  }
})

// 监听初始容器码变化，用于修改配送单场景
watch(() => props.initialContainers, async (newInitialContainers) => {
  console.log('=== 监听到初始容器码变化 ===')
  console.log('初始容器码:', newInitialContainers)
  
  if (!newInitialContainers || newInitialContainers.length === 0) {
    console.log('没有初始容器码，保持当前选择状态')
    return
  }
  
  // 等待容器数据加载完成
  if (allContainers.value.length === 0) {
    console.log('等待容器数据加载...')
    await loadAllContainers()
  }
  
  // 根据容器码找到对应的容器对象
  const matchedContainers = []
  
  for (const containerCode of newInitialContainers) {
    console.log(`正在查找容器码: ${containerCode}`)
    
    const matchedContainer = allContainers.value.find(container => {
      const currentContainerCode = getContainerCodeDisplay(container)
      const isMatch = currentContainerCode === containerCode
      
      if (isMatch) {
        console.log(`找到匹配的容器: ${containerCode}`, container)
      }
      
      return isMatch
    })
    
    if (matchedContainer) {
      matchedContainers.push(matchedContainer)
    } else {
      console.warn(`未找到容器码 ${containerCode} 对应的容器`)
    }
  }
  
  console.log(`成功匹配 ${matchedContainers.length} 个初始容器`)
  
  if (matchedContainers.length > 0) {
    // 设置选中的容器
    selectedContainers.value = matchedContainers
    console.log('已设置初始选中容器:', selectedContainers.value.map(c => getContainerCodeDisplay(c)))
    
    // 同步更新父组件的 modelValue
    nextTick(() => {
      const modelValue = {
        destination: selectedDestination.value,
        containers: matchedContainers,
        container: matchedContainers.length > 0 ? matchedContainers[0].id : ''
      }
      
      console.log('同步更新父组件 modelValue:', modelValue)
      emit('update:modelValue', modelValue)
      
      // 发送容器选择事件
      const eventData = {
        action: 'initialize',
        selectedContainers: matchedContainers,
        containerCodes: matchedContainers.map(c => getContainerCodeDisplay(c)),
        containerIds: matchedContainers.map(c => c.id || c.rowid),
        metadata: {
          destination: selectedDestination.value,
          totalCount: matchedContainers.length,
          timestamp: new Date().toISOString(),
          sourceComponent: 'ContainerFilter'
        }
      }
      
      emit('container-selected', eventData)
      console.log('已发送初始化容器选择事件')
    })
  }
}, { immediate: true })

// 监听外部目的地变化
watch(() => props.externalDestination, (newDestination) => {
  if (newDestination && newDestination !== selectedDestination.value) {
    selectedDestination.value = newDestination
    handleDestinationChange()
  }
}, { immediate: true })

watch([selectedDestination, selectedContainers], ([destination, containers]) => {
  // 防止循环更新
  if (isUpdatingFromParent.value) {
    console.log('跳过容器选择监听器的循环更新')
    return
  }
  
  console.log('=== 容器选择监听器触发 ===')
  console.log('目的地:', destination)
  console.log('选中容器数量:', containers.length)
  
  // 避免循环更新：只在数据确实变化时才进行处理
  if (containers.length === 0) {
    console.log('=== 清空容器选择 ===')
    
    nextTick(() => {
      emit('update:modelValue', {
        destination,
        containers: [],
        container: ''
      })
      
      emit('container-selected', {
        action: 'select',
        selectedContainers: [],
        containerCodes: [],
        containerIds: [],
        metadata: {
          destination: destination,
          totalCount: 0,
          timestamp: new Date().toISOString(),
          sourceComponent: 'ContainerFilter'
        }
      })
    })
    return
  }
  
  // Debug: 选中的容器详情
  
  // 构建传递给父组件的数据 - 确保包含完整的容器信息
  const modelValue = {
    destination,
    containers: containers, // 这里必须包含完整的容器对象
    // 兼容旧版本的单容器字段
    container: containers.length > 0 ? containers[0].id : ''
  }
  
  console.log('=== 设置父组件的modelValue ===')
  // Debug: modelValue.containers
  
  // === 预处理容器数据 ===
  console.log('=== 强制触发容器选择事件 ===')
  
  const processedContainers = containers.map(container => {
    const containerCode = getContainerCodeDisplay(container)
    console.log(`预处理容器 ${container.id}: 容器码=${containerCode}`)
    
    return {
      ...container,
      // 确保容器码字段存在
      extractedContainerCode: containerCode,
      // 保留原始数据
      originalRawData: container.rawData
    }
  })
  
  // 发送增强的容器选择事件
  const enhancedEventData = {
    container: processedContainers[0], // 第一个容器作为主容器
    isSelected: true,
    selectedContainers: processedContainers,
    action: 'select',
    // 新增：直接提供容器码数组
    containerCodes: processedContainers.map(c => c.extractedContainerCode),
    // 新增：提供容器ID数组
    containerIds: processedContainers.map(c => c.id || c.rowid),
    // 新增：元数据
    metadata: {
      destination: destination,
      totalCount: processedContainers.length,
      timestamp: new Date().toISOString(),
      sourceComponent: 'ContainerFilter'
    }
  }
  
  console.log('=== 发送增强的容器选择事件 ===')
  console.log('事件数据:', enhancedEventData)
  console.log('容器码数组:', enhancedEventData.containerCodes)
  console.log('容器ID数组:', enhancedEventData.containerIds)
  
  // 使用nextTick避免同步更新 - 所有的emit操作都延迟执行
  nextTick(() => {
    emit('update:modelValue', modelValue)
    emit('container-selected', enhancedEventData)
    
    // === 移除直接访问父组件的代码，减少耦合和错误 ===
  })
}, { deep: true })

// 生命周期
onMounted(() => {
  loadAllContainers()
})

// 方法
async function loadAllContainers() {
  loadingContainers.value = true
  try {
    console.log('加载所有容器数据...')
    const result = await deliveryApi.getContainersByWorksheet()
    
    if (result && Array.isArray(result)) {
      allContainers.value = result
      console.log(`已加载 ${result.length} 个容器`)
      console.log('容器数据示例:', result.slice(0, 2))
      
      // 调试：检查容器状态分布
      const statusDistribution = {}
      result.forEach(container => {
        const status = getContainerStatus(container)
        statusDistribution[status || '未知状态'] = (statusDistribution[status || '未知状态'] || 0) + 1
      })
      console.log('容器状态分布:', statusDistribution)
    } else {
      allContainers.value = []
      console.log('未获取到容器数据')
    }
  } catch (error) {
    console.error('加载容器失败:', error)
    allContainers.value = []
  } finally {
    loadingContainers.value = false
  }
}

async function handleDestinationChange() {
  console.log('发运目的地变更:', selectedDestination.value)
  
  // 清空之前的容器选择和详情
  selectedContainers.value = []
  containerDetailsMap.value = {}
  
  if (!selectedDestination.value) {
    return
  }
  
  // 如果当前容器列表为空，重新加载
  if (allContainers.value.length === 0) {
    await loadAllContainers()
  }
  
  console.log(`筛选结果: ${filteredContainers.value.length} 个匹配的容器`)
  
  // 调试：显示筛选后容器的状态
  if (filteredContainers.value.length > 0) {
    const filteredStatuses = filteredContainers.value.map(container => ({
      id: container.id,
      status: getContainerStatus(container)
    }))
    console.log('筛选后的容器状态:', filteredStatuses)
  }
}

// 容器选择相关方法
function isContainerSelected(containerId) {
  const isSelected = selectedContainers.value.some(c => c.id === containerId)
  console.log(`检查容器 ${containerId} 是否选中:`, isSelected, '当前选中的容器:', selectedContainers.value.map(c => c.id))
  return isSelected
}

function toggleContainer(container) {
  const isSelected = isContainerSelected(container.id)
  
  console.log('=== 容器选择操作 ===')
  console.log('容器ID:', container.id)
  console.log('当前选择状态:', isSelected)
  console.log('容器完整数据:', container)
  
  if (isSelected) {
    // 取消选择
    selectedContainers.value = selectedContainers.value.filter(c => c.id !== container.id)
    // 同时清除详情数据和展开状态
    delete containerDetailsMap.value[container.id]
    delete loadingDetailsMap.value[container.id]
    delete expandedDetailsMap.value[container.id]
    console.log('已取消选择容器:', container.id)
  } else {
    // 添加选择（但不自动加载详情）
    selectedContainers.value.push(container)
    console.log('已添加选择容器:', container.id)
  }
  
  // Debug: 当前选中的所有容器
  
  // 发送容器选择事件（仅用于UI状态更新）
  emit('container-selected', {
    container,
    isSelected: !isSelected,
    selectedContainers: selectedContainers.value,
    action: 'select' // 明确标识这是选择操作，不是创建操作
  })
  
  console.log('已发送容器选择事件，包含容器数量:', selectedContainers.value.length)
}

// 移除选中的容器
function removeSelectedContainer(containerToRemove) {
  console.log('=== 移除容器操作 ===')
  console.log('要移除的容器:', containerToRemove)
  
  // 从选中列表中移除指定容器
  selectedContainers.value = selectedContainers.value.filter(c => c.id !== containerToRemove.id)
  
  // 同时清除该容器的详情数据和展开状态
  delete containerDetailsMap.value[containerToRemove.id]
  delete loadingDetailsMap.value[containerToRemove.id]
  delete expandedDetailsMap.value[containerToRemove.id]
  
  console.log('容器移除后，剩余选中容器数量:', selectedContainers.value.length)
  
  // 发送移除事件，让父组件知道容器被移除了
  const eventData = {
    action: 'remove',
    removedContainer: containerToRemove,
    selectedContainers: selectedContainers.value,
    containerCodes: selectedContainers.value.map(c => getContainerCodeDisplay(c)),
    containerIds: selectedContainers.value.map(c => c.id || c.rowid),
    metadata: {
      destination: selectedDestination.value,
      totalCount: selectedContainers.value.length,
      timestamp: new Date().toISOString(),
      sourceComponent: 'ContainerFilter'
    }
  }
  
  emit('container-selected', eventData)
  console.log('已发送容器移除事件')
}

// 清空所有选中的容器
function clearAllSelectedContainers() {
  console.log('=== 清空所有选中容器 ===')
  
  const previousCount = selectedContainers.value.length
  
  // 清空选中列表
  selectedContainers.value = []
  
  // 清空所有相关数据
  containerDetailsMap.value = {}
  loadingDetailsMap.value = {}
  expandedDetailsMap.value = {}
  
  console.log(`已清空 ${previousCount} 个选中容器`)
  
  // 发送清空事件
  const eventData = {
    action: 'clear',
    selectedContainers: [],
    containerCodes: [],
    containerIds: [],
    metadata: {
      destination: selectedDestination.value,
      totalCount: 0,
      previousCount: previousCount,
      timestamp: new Date().toISOString(),
      sourceComponent: 'ContainerFilter'
    }
  }
  
  emit('container-selected', eventData)
  console.log('已发送清空容器事件')
}


async function loadContainerDetails(containerId) {
  if (loadingDetailsMap.value[containerId]) return
  
  loadingDetailsMap.value[containerId] = true
  
  try {
    console.log('=== 开始获取容器详情 ===')
    console.log('容器ID:', containerId)
    
    // 获取容器信息
    const container = allContainers.value.find(c => c.id === containerId)
    console.log('找到的容器数据:', container)
    
    if (!container) {
      console.error('未找到容器数据:', containerId)
      containerDetailsMap.value[containerId] = []
      return
    }
    
    // 获取容器码
    const containerCode = getContainerCodeDisplay(container)
    console.log('容器码:', containerCode)
    console.log('容器原始数据:', container.rawData)
    
    if (!containerCode || containerCode === '未知容器') {
      console.error('无法获取有效的容器码')
      containerDetailsMap.value[containerId] = []
      return
    }
    
    // 构建API请求参数
    const requestBody = {
      appKey: API_CONFIG.appKey,
      sign: API_CONFIG.sign,
      worksheetId: WORKSHEET_IDS.CONTAINERS,
      pageSize: 50,
      pageIndex: 1,
      filters: [{
        controlId: CONTAINER_FIELDS.CONTAINER_CODE,
        dataType: 2,
        spliceType: 1,
        filterType: 1,
        values: [containerCode]
      }]
    }
    
    console.log('API请求参数:', requestBody)
    
    // 首先测试不带筛选条件的API调用，获取所有数据
    console.log('=== 先测试获取所有容器详情数据 ===')
    const testRequestBody = {
      appKey: API_CONFIG.appKey,
      sign: API_CONFIG.sign,
      worksheetId: WORKSHEET_IDS.CONTAINERS,
      pageSize: 10,
      pageIndex: 1
    }
    
    const testResult = await fetch(`${API_CONFIG.baseURL}/getFilterRows`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(testRequestBody)
    })
    
    if (testResult.ok) {
      const testData = await testResult.json()
      console.log('测试API响应（前10条数据）:', testData)
      
      // 检查数据中是否有容器码字段
      if (testData.rows && testData.rows.length > 0) {
        const firstRow = testData.rows[0]
        console.log('第一条记录的字段:', Object.keys(firstRow))
        console.log('容器码字段值（CONTAINER_CODE）:', firstRow[CONTAINER_FIELDS.CONTAINER_CODE])
        
        // 查找匹配的容器码
        const matchingRow = testData.rows.find(row => 
          row[CONTAINER_FIELDS.CONTAINER_CODE] === containerCode
        )
        
        if (matchingRow) {
          console.log('找到匹配的容器码记录:', matchingRow)
          containerDetailsMap.value[containerId] = [matchingRow]
          return
        } else {
          console.log('在数据中未找到匹配的容器码:', containerCode)
          console.log('现有的容器码值:', testData.rows.map(row => row[CONTAINER_FIELDS.CONTAINER_CODE]))
        }
      }
    }
    
    console.log('=== 使用筛选条件的API调用 ===')
    const result = await fetch(`${API_CONFIG.baseURL}/getFilterRows`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestBody)
    })
    
    if (!result.ok) {
      throw new Error(`API请求失败: ${result.status}`)
    }
    
    const data = await result.json()
    console.log('=== API响应数据 ===')
    console.log('完整响应:', data)
    console.log('响应状态:', result.status)
    
    // 处理响应数据，适应不同的响应格式
    let actualRows = null
    if (data.rows) {
      actualRows = data.rows
      console.log('使用 data.rows，数据长度:', actualRows.length)
    } else if (data.data && data.data.rows) {
      actualRows = data.data.rows
      console.log('使用 data.data.rows，数据长度:', actualRows.length)
    } else if (data.data && Array.isArray(data.data)) {
      actualRows = data.data
      console.log('使用 data.data，数据长度:', actualRows.length)
    } else {
      console.log('响应数据结构异常')
    }
    
    if (actualRows && Array.isArray(actualRows) && actualRows.length > 0) {
      containerDetailsMap.value[containerId] = actualRows
      console.log(`=== 成功获取 ${actualRows.length} 条容器详情记录 ===`)
      console.log('第一条记录示例:', actualRows[0])
    } else {
      containerDetailsMap.value[containerId] = []
      console.log('=== 未找到容器详情数据 ===')
      console.log('可能的原因：')
      console.log('1. 容器码不匹配')
      console.log('2. 工作表ID不正确')
      console.log('3. 字段ID不正确')
      console.log('4. 数据不存在')
    }
    
  } catch (error) {
    console.error('=== 获取容器详情失败 ===')
    console.error('错误信息:', error)
    console.error('容器ID:', containerId)
    console.error('完整错误:', error.stack)
    containerDetailsMap.value[containerId] = []
  } finally {
    loadingDetailsMap.value[containerId] = false
    console.log('=== 容器详情获取流程结束 ===')
  }
}

function toggleContainerDetails(containerId) {
  const isExpanded = expandedDetailsMap.value[containerId]
  
  if (isExpanded) {
    // 折叠详情
    expandedDetailsMap.value[containerId] = false
  } else {
    // 展开详情
    expandedDetailsMap.value[containerId] = true
    
    // 如果没有加载过详情，则加载
    if (!containerDetailsMap.value[containerId]) {
      loadContainerDetails(containerId)
    }
  }
}

function isContainerExpanded(containerId) {
  return !!expandedDetailsMap.value[containerId]
}

function closeContainerDetails(containerId) {
  expandedDetailsMap.value[containerId] = false
}

// 辅助方法
function getContainerStatus(container) {
  // 使用指定的字段ID获取容器状态
  const statusFieldId = CONTAINER_FIELDS.STATUS
  
  console.log('=== 获取容器状态 ===')
  console.log('容器对象:', container)
  console.log('状态字段ID:', statusFieldId)
  console.log('状态字段ID类型:', typeof statusFieldId)
  console.log('状态字段ID是否为空:', !statusFieldId)
  
  if (!container) {
    console.log('容器对象为空')
    return ''
  }
  
  let containerStatus = ''
  
  // 方法1: 从rawData中获取
  if (container.rawData && statusFieldId && container.rawData[statusFieldId]) {
    containerStatus = container.rawData[statusFieldId]
    console.log('从rawData获取的状态:', containerStatus)
  }
  
  // 方法2: 直接从容器对象获取
  if (!containerStatus && statusFieldId && container[statusFieldId]) {
    containerStatus = container[statusFieldId]
    console.log('从容器对象获取的状态:', containerStatus)
  }
  
  // 方法3: 尝试使用'containerstate'字段（备用方案）
  if (!containerStatus && container.rawData && container.rawData['containerstate']) {
    containerStatus = container.rawData['containerstate']
    console.log('从rawData使用containerstate获取的状态:', containerStatus)
  }
  
  // 方法4: 直接从容器对象使用'containerstate'字段
  if (!containerStatus && container['containerstate']) {
    containerStatus = container['containerstate']
    console.log('从容器对象使用containerstate获取的状态:', containerStatus)
  }
  
  // 方法5: 使用getFieldValue函数
  if (!containerStatus && statusFieldId) {
    containerStatus = getFieldValue(
      container.rawData || container,
      statusFieldId,
      ''
    )
    console.log('使用getFieldValue获取的状态:', containerStatus)
  }
  
  console.log('最终获取的容器状态:', containerStatus)
  return containerStatus || ''
}

function isStatusInUseOnly(status) {
  if (!status) {
    console.log('容器状态为空，修改模式下不允许显示')
    return false // 修改模式下，状态为空的容器不显示
  }
  
  // 处理各种可能的状态值
  const statusStr = String(status).trim()
  console.log(`修改模式检查容器状态: "${statusStr}"`)
  
  // 检查是否为明确的"使用中"状态 - 这些容器应该显示
  const inUsePatterns = [
    '使用中',
    '使用',
    '在用',
    '已使用',
    'in_use',
    'in use',
    'using',
    'active',
    'occupied'
  ]
  
  const isInUse = inUsePatterns.some(pattern => 
    statusStr.toLowerCase().includes(pattern.toLowerCase())
  )
  
  if (isInUse) {
    console.log('容器状态为使用中，修改模式下允许显示')
    return true
  }
  
  // 修改模式下，其他所有状态（包括"待使用"、"装车中"、"已完成"等）都不显示
  console.log(`修改模式下容器状态 "${statusStr}" 不允许显示`)
  return false
}

function isStatusInUse(status) {
  if (!status) {
    console.log('容器状态为空，默认允许显示')
    return true // 如果状态为空，默认允许显示
  }
  
  // 处理各种可能的状态值
  const statusStr = String(status).trim()
  console.log(`检查容器状态: "${statusStr}"`)
  
  // 首先检查是否为"使用完成"状态 - 这些容器应该被排除
  const completedPatterns = [
    '使用完成',
    '完成使用',
    '已完成',
    '使用结束',
    '完成',
    'completed',
    'finished',
    'done',
    'used_complete',
    'usage_complete'
  ]
  
  const isCompleted = completedPatterns.some(pattern => 
    statusStr.toLowerCase().includes(pattern.toLowerCase())
  )
  
  // 如果是使用完成状态，直接返回false（不显示）
  if (isCompleted) {
    console.log('容器状态为使用完成，不显示')
    return false
  }
  
  // 检查是否为明确的"待使用"状态 - 这些容器应该被排除
  const pendingPatterns = [
    '待使用',
    '未使用',
    '等待使用',
    'pending',
    'waiting',
    'unused'
  ]
  
  const isPending = pendingPatterns.some(pattern => 
    statusStr.toLowerCase().includes(pattern.toLowerCase())
  )
  
  if (isPending) {
    console.log('容器状态为待使用，不显示')
    return false
  }
  
  // 对于其他所有状态（包括"使用中"），都允许显示
  console.log(`容器状态 "${statusStr}" 允许显示`)
  return true
}

function isStatusInUseOrLoading(status) {
  if (!status) return false
  
  // 处理各种可能的状态值
  const statusStr = String(status).trim()
  
  // 首先检查是否为"使用完成"状态 - 这些容器应该被排除
  const completedPatterns = [
    '使用完成',
    '完成使用',
    '已完成',
    '使用结束',
    '完成',
    'completed',
    'finished',
    'done',
    'used_complete',
    'usage_complete'
  ]
  
  const isCompleted = completedPatterns.some(pattern => 
    statusStr.toLowerCase().includes(pattern.toLowerCase())
  )
  
  // 如果是使用完成状态，直接返回false（不显示）
  if (isCompleted) {
    console.log('容器状态为使用完成，不显示')
    return false
  }
  
  // 检查是否为"使用中"或"装车中"状态 - 这些容器应该显示
  const inUseOrLoadingPatterns = [
    '使用中',
    '使用',
    '在用',
    '已使用',
    '装车中',
    '装车',
    '装载中',
    '装载',
    'in_use',
    'in use',
    'using',
    'loading',
    'active',
    'occupied'
  ]
  
  const isInUseOrLoading = inUseOrLoadingPatterns.some(pattern => 
    statusStr.toLowerCase().includes(pattern.toLowerCase())
  )
  
  console.log('容器状态匹配检查（包含装车中）')
  
  return isInUseOrLoading
}

function getContainerCodeDisplay(container) {
  console.log('=== 获取容器码显示 - 调试信息 ===')
  console.log('容器对象:', container)
  
  if (!container) {
    console.log('容器对象为空')
    return '未知容器'
  }
  
  let containerCode = ''
  
  // 方法1: 从rawData中获取容器码
  if (container.rawData && typeof container.rawData === 'object') {
    // 尝试多个可能的字段
    containerCode = container.rawData[CONTAINER_FIELDS.CONTAINER_CODE] || // 明道云容器码字段ID
                   container.rawData.containerCode || 
                   container.rawData.code || 
                   container.rawData.name || ''
    
    if (containerCode) {
      console.log('从rawData获取的容器码:', containerCode)
      return String(containerCode).trim()
    }
  }
  
  // 方法2: 直接从容器对象获取
  containerCode = container[CONTAINER_FIELDS.CONTAINER_CODE] || // 明道云容器码字段ID
                 container.containerCode || 
                 container.code || 
                 container.name || ''
  
  if (containerCode) {
    console.log('从容器对象直接获取的容器码:', containerCode)
    return String(containerCode).trim()
  }
  
  // 方法3: 检查是否有products字段，从中提取容器编号
  if (container.products && typeof container.products === 'string') {
    // 尝试从商品信息中提取容器编号（如果有的话）
    const productText = container.products
    const codeMatch = productText.match(/容器[编号码]?[:：]?\s*([A-Za-z0-9\-]+)/)
    if (codeMatch) {
      console.log('从商品信息中提取的容器码:', codeMatch[1])
      return codeMatch[1].trim()
    }
  }
  
  console.log('=== 容器码获取失败，使用备用方案 ===')
  console.log('container.id:', container.id)
  console.log('container.rowid:', container.rowid)
  
  // 最后备用方案：生成一个更友好的显示名称
  if (container.id && container.id.length > 8) {
    // 如果ID是长哈希，显示简化版本
    const shortId = container.id.substring(0, 8).toUpperCase()
    console.log('生成简化容器码:', `CT-${shortId}`)
    return `CT-${shortId}`
  }
  
  return container.id || container.rowid || '未知容器'
}

function shouldShowField(field) {
  // 过滤掉不需要显示的系统字段
  const hiddenFields = ['id', '_id', 'rowid', '__typename', 'utime', 'ctime', 'ownerid', 'caid']
  
  // 过滤掉空值字段
  if (!field) return false
  
  return !hiddenFields.includes(field.toLowerCase())
}

function getFieldLabel(field) {
  // 明道云字段ID映射为中文标签
  const fieldLabels = {
    // 通用字段
    'name': '名称',
    'type': '类型', 
    'status': '状态',
    'capacity': '容量',
    'weight': '重量',
    'products': '商品信息',
    'destination': '目的地',
    'createdAt': '创建时间',
    'updatedAt': '更新时间',
    
    // 明道云特定字段ID（根据实际字段配置）
    [CONTAINER_FIELDS.CONTAINER_CODE]: '容器码',
    [WORKSHEET_IDS.CONTAINERS]: '容器管理详情',
    [CONTAINER_FIELDS.CONTAINER_CODE]: '容器编号',
    [CONTAINER_FIELDS.PRODUCTS]: '商品信息',
    [CONTAINER_FIELDS.CONTAINER_SITE_INFO]: '配送站点信息',
    [CONTAINER_FIELDS.RELATION_FIELD]: '关联信息',
    
    // 常见明道云系统字段
    'rowid': 'ID',
    'utime': '更新时间',
    'ctime': '创建时间',
    'ownerid': '创建者',
    'caid': '应用ID'
  }
  
  // 如果有映射就使用中文标签，否则显示字段ID（简化显示）
  const label = fieldLabels[field]
  if (label) {
    return label
  }
  
  // 对于未知的字段ID，显示简化版本
  if (field && field.length > 10 && field.match(/^[a-f0-9]+$/)) {
    return `字段(${field.substring(0, 8)}...)`
  }
  
  return field || '未知字段'
}

function formatFieldValue(value) {
  if (value === null || value === undefined || value === '') {
    return '未设置'
  }
  
  // 处理数组
  if (Array.isArray(value)) {
    if (value.length === 0) return '无数据'
    return value.join(', ')
  }
  
  // 处理对象
  if (typeof value === 'object') {
    // 如果是明道云的引用对象，提取有用信息
    if (value.name || value.title) {
      return value.name || value.title
    }
    
    // 如果对象很简单，尝试提取值
    const keys = Object.keys(value)
    if (keys.length === 1) {
      return formatFieldValue(value[keys[0]])
    }
    
    // 复杂对象显示JSON
    try {
      return JSON.stringify(value, null, 2)
    } catch {
      return '复杂对象数据'
    }
  }
  
  // 处理时间戳
  const valueStr = String(value)
  if (valueStr.match(/^\d{13}$/)) {
    try {
      return new Date(parseInt(valueStr)).toLocaleString('zh-CN')
    } catch {
      return valueStr
    }
  }
  
  // 处理长文本，截断显示
  if (valueStr.length > 100) {
    return valueStr.substring(0, 100) + '...'
  }
  
  return valueStr
}

// 商品信息提取函数
function getProductName(detail) {
  // 使用指定的字段ID获取商品名称
  const productNameFieldId = CONTAINER_FIELDS.PRODUCT_NAME
  
  if (detail[productNameFieldId]) {
    return String(detail[productNameFieldId])
  }
  
  return '未知商品'
}

function getProductQuantity(detail) {
  // 使用指定的字段ID获取数量
  const quantityFieldId = CONTAINER_FIELDS.QUANTITY
  
  if (detail[quantityFieldId] !== undefined && detail[quantityFieldId] !== null) {
    const qty = parseFloat(detail[quantityFieldId])
    if (!isNaN(qty)) {
      return qty.toString()
    }
  }
  
  return '1' // 默认数量
}

function getTotalItems(details) {
  if (!details || !Array.isArray(details)) return 0
  return details.length
}

// 动画钩子函数
function onDetailsEnter(el) {
  el.style.height = '0px'
  el.style.opacity = '0'
  
  // 强制重绘
  el.offsetHeight
  
  // 设置动画
  el.style.transition = 'height 0.3s ease, opacity 0.3s ease'
  el.style.height = el.scrollHeight + 'px'
  el.style.opacity = '1'
}

function onDetailsLeave(el) {
  el.style.height = el.scrollHeight + 'px'
  
  // 强制重绘
  el.offsetHeight
  
  // 设置动画
  el.style.transition = 'height 0.3s ease, opacity 0.3s ease'
  el.style.height = '0px'
  el.style.opacity = '0'
}

// 搜索相关方法
function handleSearchInput() {
  // 搜索输入时自动触发精准筛选（通过计算属性filteredContainers）
  console.log('精准搜索输入:', containerCodeSearch.value)
}

function handleSearchEnter() {
  // Enter键时的处理
  if (containerCodeSearch.value.trim() && filteredContainers.value.length === 1) {
    // 如果精准匹配到一个结果，自动选择
    const container = filteredContainers.value[0]
    toggleContainer(container)
  }
}

function clearSearch() {
  containerCodeSearch.value = ''
  console.log('清除精准搜索')
}

// 获取容器配送站点信息
function getContainerSiteInfo(container) {
  if (!container) {
    return ''
  }
  
  // 尝试从rawData中获取配送站点信息
  if (container.rawData) {
    const siteInfo = container.rawData[CONTAINER_FIELDS.CONTAINER_SITE_INFO] || // 配送站点信息字段ID
                    container.rawData.siteInfo || 
                    container.rawData.site || ''
    if (siteInfo) {
      return String(siteInfo).trim()
    }
  }
  
  // 尝试从容器对象直接获取
  const siteInfo = container[CONTAINER_FIELDS.CONTAINER_SITE_INFO] || 
                  container.siteInfo || 
                  container.site || ''
  if (siteInfo) {
    return String(siteInfo).trim()
  }
  
  return ''
}
</script>

<style scoped>
.container-filter {
  background: white;
  border-radius: 8px;
  padding: 1.5rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-left: 4px solid #f8b300;
}

.filter-section {
  margin-bottom: 1.5rem;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group.disabled {
  opacity: 0.6;
}

.form-header {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-bottom: 1rem;
}

.form-label {
  font-weight: 600;
  color: #333;
  font-size: 1rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0;
}

.selected-count {
  color: #f8b300;
  font-weight: 500;
  font-size: 0.9rem;
}

.container-search {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 1rem;
}

.search-input-wrapper {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  background: white;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  padding: 0.5rem;
  transition: all 0.3s ease;
}

.search-input-wrapper:focus-within {
  border-color: #f8b300;
  box-shadow: 0 0 0 0.2rem rgba(248, 179, 0, 0.25);
}

.search-input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 1rem;
  padding: 0.5rem;
  color: #333;
  background: transparent;
}

.search-input::placeholder {
  color: #999;
  font-style: italic;
}

.search-actions {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.search-count {
  font-size: 0.85rem;
  color: #666;
  background: #e9ecef;
  padding: 0.25rem 0.5rem;
  border-radius: 12px;
  font-weight: 500;
}

.clear-search-btn {
  background: #dc3545;
  border: none;
  color: white;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 1.2rem;
  font-weight: bold;
  transition: all 0.2s ease;
}

.clear-search-btn:hover {
  background: #c82333;
  transform: scale(1.1);
}

.placeholder-message, .empty-message {
  text-align: center;
  padding: 2rem;
  color: #666;
  background: #f8f9fa;
  border: 2px dashed #dee2e6;
  border-radius: 8px;
  font-size: 1rem;
}

/* 已选择容器区域样式 */
.selected-containers-section {
  margin-bottom: 1.5rem;
  padding: 1rem;
  background: linear-gradient(135deg, #e8f5e8 0%, #f0f8f0 100%);
  border: 2px solid #28a745;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(40, 167, 69, 0.1);
}

.selected-title {
  margin: 0 0 1rem 0;
  font-size: 1rem;
  font-weight: 600;
  color: #155724;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.selected-title .icon {
  background: #28a745;
  color: white;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.8rem;
  font-weight: bold;
}

.selected-container-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  margin-bottom: 1rem;
}

.selected-container-tag {
  background: #28a745;
  color: white;
  padding: 0.5rem 0.75rem;
  border-radius: 20px;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-weight: 500;
  box-shadow: 0 2px 6px rgba(40, 167, 69, 0.3);
  transition: all 0.2s ease;
  border: 2px solid #28a745;
  cursor: pointer;
  user-select: none;
}

.selected-container-tag:hover {
  background: #218838;
  border-color: #1e7e34;
  transform: translateY(-1px);
  box-shadow: 0 4px 10px rgba(40, 167, 69, 0.4);
}

.selected-container-tag:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(40, 167, 69, 0.3);
}

.container-code {
  font-family: 'Courier New', monospace;
  font-size: 0.9rem;
  font-weight: 600;
  letter-spacing: 0.5px;
  text-transform: uppercase;
}

.remove-container-btn {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 1.2rem;
  font-weight: bold;
  transition: all 0.2s ease;
  line-height: 1;
}

.remove-container-btn:hover {
  background: #dc3545;
  transform: scale(1.1);
  box-shadow: 0 2px 6px rgba(220, 53, 69, 0.3);
}

.remove-container-btn:active {
  transform: scale(0.95);
}

.selected-actions {
  display: flex;
  justify-content: center;
  padding-top: 0.5rem;
  border-top: 1px solid rgba(40, 167, 69, 0.2);
  margin-bottom: 0.75rem;
}

.selected-hint {
  text-align: center;
  padding: 0.5rem;
  background: rgba(40, 167, 69, 0.05);
  border-radius: 6px;
  border: 1px dashed rgba(40, 167, 69, 0.2);
}

.selected-hint small {
  color: #155724;
  font-size: 0.8rem;
  line-height: 1.3;
  display: block;
}

.clear-all-btn {
  background: #dc3545;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  font-size: 0.9rem;
  transition: all 0.2s ease;
  box-shadow: 0 2px 6px rgba(220, 53, 69, 0.2);
}

.clear-all-btn:hover {
  background: #c82333;
  transform: translateY(-1px);
  box-shadow: 0 4px 10px rgba(220, 53, 69, 0.3);
}

.clear-all-btn:active {
  transform: translateY(0);
}

.no-results-icon {
  font-size: 2rem;
  margin-bottom: 0.5rem;
}

.no-results-text {
  font-weight: 600;
  color: #333;
  margin-bottom: 0.5rem;
}

.no-results-hint {
  font-size: 0.9rem;
  color: #666;
  font-style: italic;
}

.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.75rem;
  padding: 2rem;
  color: #666;
  background: #f8f9fa;
  border-radius: 8px;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid #e0e0e0;
  border-top: 2px solid #f8b300;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 容器列表样式 */
.container-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  max-height: 500px;
  overflow-y: auto;
  padding: 0.5rem;
}

.container-card {
  border: 2px solid #e9ecef;
  border-radius: 12px;
  background: white;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.container-card:hover {
  border-color: #f8b300;
  box-shadow: 0 4px 12px rgba(248, 179, 0, 0.15);
  transform: translateY(-2px);
}

.container-card.selected {
  border-color: #28a745;
  background: linear-gradient(135deg, rgba(40, 167, 69, 0.05) 0%, rgba(40, 167, 69, 0.02) 100%);
  box-shadow: 0 4px 15px rgba(40, 167, 69, 0.15);
  transform: translateY(-1px);
  position: relative;
}

.container-card.selected::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #28a745, #34ce57, #28a745);
  border-radius: 12px 12px 0 0;
}

.container-card.has-details {
  border-color: #17a2b8;
}

.container-main {
  display: flex;
  align-items: center;
  gap: 1rem;
  cursor: pointer;
  padding: 0.75rem;
  border-radius: 8px;
  transition: all 0.3s ease;
  position: relative;
}

.container-main:hover {
  background: rgba(248, 179, 0, 0.05);
  transform: translateY(-1px);
}

.container-card.selected .container-main {
  background: linear-gradient(135deg, rgba(40, 167, 69, 0.1) 0%, rgba(40, 167, 69, 0.05) 100%);
  border-left: 4px solid #28a745;
}

.container-selection-indicator {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  flex-shrink: 0;
  position: relative;
}

.selection-checkbox {
  display: flex;
  align-items: center;
}

.selection-checkbox input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
  accent-color: #28a745;
  transform: scale(1.1);
}

.selection-checkmark {
  color: #28a745;
  font-size: 1.2rem;
  font-weight: bold;
  animation: checkmarkAppear 0.3s ease-out;
  text-shadow: 0 0 3px rgba(40, 167, 69, 0.3);
}

@keyframes checkmarkAppear {
  0% {
    opacity: 0;
    transform: scale(0.5);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

.container-info {
  flex: 1;
}

.container-id-wrapper {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  margin-bottom: 0.5rem;
}

.container-id {
  font-size: 1.1rem;
  font-weight: 600;
  color: #333;
  font-family: 'Courier New', monospace;
  letter-spacing: 0.5px;
}

.selected-badge {
  background: #28a745;
  color: white;
  padding: 0.2rem 0.5rem;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  animation: badgeAppear 0.3s ease-out;
  box-shadow: 0 2px 4px rgba(40, 167, 69, 0.3);
}

@keyframes badgeAppear {
  0% {
    opacity: 0;
    transform: scale(0.8) translateY(-5px);
  }
  100% {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

.container-site {
  color: #666;
  font-size: 0.9rem;
  line-height: 1.4;
  background: #f8f9fa;
  padding: 0.5rem;
  border-radius: 6px;
  border-left: 3px solid #007bff;
  margin-bottom: 0.5rem;
}

.container-site strong {
  color: #333;
  margin-right: 0.5rem;
}

.container-site .site-info {
  color: #007bff;
  font-weight: 500;
}

.container-products {
  color: #666;
  font-size: 0.9rem;
  line-height: 1.4;
  background: #f8f9fa;
  padding: 0.5rem;
  border-radius: 6px;
  border-left: 3px solid #28a745;
}


.container-actions {
  flex-shrink: 0;
  display: flex;
  align-items: center;
}

.toggle-details-btn {
  background: #007bff;
  border: none;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 123, 255, 0.2);
}

.toggle-details-btn:hover {
  background: #0056b3;
  transform: scale(1.1);
  box-shadow: 0 4px 8px rgba(0, 123, 255, 0.3);
}

.toggle-details-btn.expanded {
  background: #28a745;
}

.toggle-details-btn.expanded:hover {
  background: #1e7e34;
}

.toggle-icon {
  color: white;
  font-size: 0.8rem;
  font-weight: bold;
  transition: transform 0.3s ease;
}

.toggle-details-btn.expanded .toggle-icon {
  transform: rotate(180deg);
}


/* 内联详情样式 */
.container-details-inline {
  border-top: 1px solid #e9ecef;
  background: #f8f9fa;
  padding: 1rem;
  margin-top: 0;
  overflow: hidden;
}

/* 详情展开折叠动画 */
.details-slide-enter-active,
.details-slide-leave-active {
  transition: all 0.3s ease;
}

.details-slide-enter-from {
  height: 0;
  opacity: 0;
  transform: translateY(-10px);
}

.details-slide-leave-to {
  height: 0;
  opacity: 0;
  transform: translateY(-10px);
}

.details-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
  font-weight: 600;
  color: #333;
}

.loading-text {
  font-size: 0.9rem;
  color: #f8b300;
  font-weight: 500;
}

.details-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.75rem;
  padding: 2rem;
  color: #666;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px dashed #dee2e6;
}

.close-details-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #666;
  padding: 0;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}

.close-details-btn:hover {
  background: #e9ecef;
}

.details-list {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  position: relative;
  padding-top: 8px;
}

.item-count-badge {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #007bff;
  color: white;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.8rem;
  font-weight: 600;
  box-shadow: 0 2px 4px rgba(0, 123, 255, 0.3);
}

.product-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  max-height: 300px;
  overflow-y: auto;
  padding-right: 4px;
}

.product-list::-webkit-scrollbar {
  width: 6px;
}

.product-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.product-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.product-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.product-item {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 12px;
  transition: all 0.2s ease;
}

.product-item:hover {
  background: #ffffff;
  border-color: #007bff;
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.1);
  transform: translateY(-1px);
}

.product-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-name {
  font-size: 1rem;
  font-weight: 600;
  color: #333;
  flex: 1;
  margin-right: 12px;
}

.product-quantity {
  background: #28a745;
  color: white;
  padding: 4px 8px;
  border-radius: 50%;
  font-size: 0.8rem;
  font-weight: 600;
  min-width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  white-space: nowrap;
}

.detail-header {
  font-weight: 600;
  color: #333;
  margin-bottom: 0.75rem;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid #e9ecef;
}

.field-rows {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.field-row {
  display: flex;
  align-items: flex-start;
  gap: 1rem;
  margin-bottom: 0.5rem;
}

.field-label {
  min-width: 120px;
  font-weight: 600;
  color: #444;
  flex-shrink: 0;
  background: #f8f9fa;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.9rem;
}

.field-value {
  flex: 1;
  color: #333;
  word-break: break-word;
  padding: 4px 8px;
  background: white;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  font-size: 0.9rem;
  line-height: 1.4;
}

.no-details {
  text-align: center;
  padding: 1rem;
  opacity: 0.6;
}

.empty-icon {
  font-size: 1.5rem;
  opacity: 0.5;
}


/* 响应式设计 */
@media (max-width: 768px) {
  .container-filter {
    padding: 1rem;
  }
  
  .form-header {
    gap: 0.75rem;
  }
  
  .container-search {
    padding: 0.75rem;
  }
  
  .search-input-wrapper {
    flex-direction: column;
    align-items: stretch;
    gap: 0.5rem;
    padding: 0.75rem;
  }
  
  .search-actions {
    justify-content: space-between;
  }
  
  .search-input {
    font-size: 16px; /* 防止iOS缩放 */
    padding: 0.75rem;
  }
  
  .container-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.75rem;
  }
  
  .container-actions {
    width: 100%;
  }
  
  .field-row {
    flex-direction: column;
    gap: 0.25rem;
  }
  
  .field-label {
    min-width: auto;
  }
  
  .details-header-info {
    flex-direction: column;
    gap: 0.5rem;
    text-align: center;
  }
  
  .product-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }
  
  .product-quantity {
    align-self: flex-end;
  }
  
  .no-results-icon {
    font-size: 1.5rem;
  }
  
  .no-results-text {
    font-size: 1rem;
  }
  
  .no-results-hint {
    font-size: 0.85rem;
  }
  
  /* 容器选择指示器移动端优化 */
  .container-selection-indicator {
    gap: 0.3rem;
  }
  
  .selection-checkbox input[type="checkbox"] {
    width: 20px;
    height: 20px;
    transform: scale(1);
  }
  
  .selection-checkmark {
    font-size: 1rem;
  }
  
  .container-id-wrapper {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
    margin-bottom: 0.75rem;
  }
  
  .container-id {
    font-size: 1rem;
    letter-spacing: 0.3px;
  }
  
  .selected-badge {
    font-size: 0.7rem;
    padding: 0.15rem 0.4rem;
    border-radius: 10px;
  }
  
  /* 已选择容器区域移动端优化 */
  .selected-containers-section {
    padding: 0.75rem;
    margin-bottom: 1rem;
  }
  
  .selected-title {
    font-size: 0.95rem;
    margin-bottom: 0.75rem;
  }
  
  .selected-title .icon {
    width: 20px;
    height: 20px;
    font-size: 0.7rem;
  }
  
  .selected-container-tags {
    gap: 0.4rem;
    margin-bottom: 0.75rem;
  }
  
  .selected-container-tag {
    padding: 0.4rem 0.6rem;
    font-size: 0.85rem;
    border-radius: 16px;
    gap: 0.4rem;
  }
  
  .container-code {
    font-size: 0.8rem;
    letter-spacing: 0.3px;
  }
  
  .remove-container-btn {
    width: 18px;
    height: 18px;
    font-size: 1rem;
    min-width: 44px; /* 确保触摸目标足够大 */
    min-height: 44px;
    margin: -13px; /* 扩大触摸区域但保持视觉大小 */
    padding: 13px;
  }
  
  .clear-all-btn {
    padding: 0.75rem 1rem;
    font-size: 0.9rem;
    min-height: 44px;
  }
  
  .selected-actions {
    padding-top: 0.75rem;
  }
}

/* 滚动条样式优化 */
.container-list::-webkit-scrollbar {
  width: 8px;
}

.container-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.container-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.container-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>